import axios from 'axios'
import router from '@/router'

import {
	Notification,
	Message
} from 'element-ui';

import store from '@/store';

import config from '@/config';

const baseUrl = config.baseUrl.dev

class Http {
	//构造函数
	constructor(baseUrl) {
		this.baseUrl = baseUrl;
		this.queue = {};
		this.loading = false;
	}

	getInsideConfig() {
		const config = {
			baseURL: this.baseUrl,
			//超时
			timeout: 30000,
			// headers: {
			// 	Authorization: store.getters.token
			// }
		}
		return config;
	}

	interceptors(instance, url) {
		//请求拦截
		instance.interceptors.request.use(config => {
			return config;
		}, error => {
			return Promise.reject(error);
		})

		//响应拦截器
		instance.interceptors.response.use(res => {
			// if (process.env.NODE_ENV === 'development') {
			// 	//console.group(`[请求地址] ${res.config.url}`);
			// 	//console.info(`[请求地址] ${res.config.url}`, `[请求数据] ${res.config.data}`);
			// 	console.log(res);
			// 	console.groupEnd()
			// }
			return this.handleResponse(res);
		}, error => {
			Notification.closeAll();
			Message.closeAll();

			//网络错误
			if (!error.response) {
				Notification.error({
					title: '系统提示',
					message: '网络错误,请稍后重试!',
					duration: 3000
				});
				return Promise.reject(error);
			}

			if (error.response && error.response.status === 401) {
				Notification.warning({
					title: '系统提示',
					message: '登录失效,请重新登录!',
					duration: 3000
				});
				// store.commit('logout');
				// router.push('/passport/login');
			} else {
				Notification.error({
					title: '系统错误',
					message: '服务异常,请联系管理员重试!',
					duration: 3000
				});
			}
			return Promise.reject(error);
		})
	}

	//返回数据处理
	handleResponse(res) {
		let {
			data,
			status
		} = res;
		if (data.code == 401) {
			Notification.closeAll();

			Notification.warning({
				title: '系统提示',
				message: '登录失效,请重新登录!',
				duration: 3000
			});
			store.commit('logout');
			router.push('/passport/login');
		} else if ([403, 404, 409, 500, 999].indexOf(data.code) != -1) {
			Message.closeAll();
			Message({
				type: 'error',
				message: data.message
			});
		}
		return data;
	}

	request(options, loading) {
		this.loading = loading;
		const instance = axios.create();
		options = Object.assign(this.getInsideConfig(), options);
		this.interceptors(instance, options.url);
		return instance(options);
	}

	get(url, params = {}, loading = false) {
		return this.request({
			url: url,
			params: params,
			method: "get"
		}, loading);
	}

	post(url, params = {}, loading = false) {
		return this.request({
			url: url,
			data: params,
			method: "post"
		}, loading);
	}

	put(url, params = {}, loading = false) {
		return this.request({
			url: url,
			data: data,
			method: "put"
		}, loading);
	}
}


export default new Http(baseUrl)